package main

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"log"
	"os"
)

//	func main() {
//		config := &ssh.ClientConfig{
//			User: "root",
//			Auth: []ssh.AuthMethod{
//				ssh.Password("root"),
//			},
//			HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
//				return nil
//			},
//		}
//		client, err := ssh.Dial("tcp", "127.0.0.1:22", config)
//		if err != nil {
//			panic("Failed to dial: " + err.Error())
//		}
//
//		// Each ClientConn can support multiple interactive sessions,
//		// represented by a Session.
//		session, err := client.NewSession()
//		if err != nil {
//			panic("Failed to create session: " + err.Error())
//		}
//		defer session.Close()
//
//		// Once a Session is created, you can execute a single command on
//		// the remote side using the Run method.
//		//var b bytes.Buffer
//		//session.Stdout = &b
//		//if err := session.Run("/usr/bin/whoami"); err != nil {
//		//	panic("Failed to run: " + err.Error())
//		//}
//		//fmt.Println(b.String())
//	}
func main() {
	// 建立SSH客户端连接
	client, err := ssh.Dial("tcp", "192.168.91.93:22", &ssh.ClientConfig{
		User:            "root",
		Auth:            []ssh.AuthMethod{ssh.Password("root")},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	})
	if err != nil {
		log.Fatalf("SSH dial error: %s", err.Error())
	}

	// 建立新会话
	session, err := client.NewSession()
	defer session.Close()
	if err != nil {
		log.Fatalf("new session error: %s", err.Error())
	}

	result, err := session.Output("ls -al")
	if err != nil {
		fmt.Fprintf(os.Stdout, "Failed to run command, Err:%s", err.Error())
		os.Exit(0)
	}
	fmt.Println(string(result))
}
